<template>
  <dialog-edit :visible.sync="dialogVisible" :editModel="'E'" :title="'菜单授权'" :api="api" :autoSave="false"
      @onSaved="onSaved" :width="'40%'">
      <el-tree :data="data" ref="menuTree" v-loading="authLoding" :props="defaultProps"
        node-key="value" :show-checkbox="true">
      </el-tree>
  </dialog-edit>
</template>
<script>
  import BaseDialog from '@/pages/BaseDialog'
  import DialogEdit from '@/components/dialog/DialogEdit'
  import { sysRoleMenu, sysMenu } from '@/api/platformApi'
  export default {
    extends: new BaseDialog(),
    components: {
      DialogEdit
    },
    props: {
      // 当前行的用户ID
      rowId: {
        type: String,
        default: ''
      }
    },
    data () {
      return {
        data: [],
        defaultProps: {
          children: 'children',
          label: 'label',
          id: 'value'
        },
        authLoding: false,
        defaultChecked: []
      }
    },
    created () {
      this.getData()
    },
    methods: {
      getData () {
        this.authLoding = true
        sysMenu.menuTree().then(res => {
          this.data = res.data
          this.get()
        }).catch(() => {
          this.authLoding = false
        })
      },
      // 获取选择用户分配的菜单
      get () {
        if (!this.rowId) return
        sysRoleMenu.get(this.rowId).then(res => {
          this.$nextTick(() => {
            let arr = res.data
            arr.map(_ => {
              this.$refs.menuTree.setChecked(_, true)
            })
          })
          this.authLoding = false
        }).catch(() => {
          this.authLoding = false
        })
      },
      // 保存用户分配的菜单
      onSaved () {
        // 获取选中的数据id
        let res = this.$refs.menuTree.getCheckedKeys().concat(this.$refs.menuTree.getHalfCheckedKeys())
        let params = {id: this.rowId, menuIds: res}
        sysRoleMenu.create(params).then(res => {
          if (res.msg === '执行成功') {
            this.success(res.msg)
            // 处理数据后重新加载菜单
            this.$store.dispatch('GetNavMenus', {'reload': true})
            this.dialogVisible = false
          } else {
            this.error(res.msg)
          }
        })
      }
    }
  }
</script>
<style scoped>
</style>
